<?php

namespace App\Http\Controllers\Activity;

use App\Activity;
use App\Lib\Util\ResponseUtil;
use Validator;
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\MenuPermissionService;
use App\Services\RouteService;
use Illuminate\Validation\Rule;
use App\BaseDictionary;
use App\Route;
use App\MenuPermission;
use App\Services\ActivityService;
use App\Services\UserGroupService;
use App\Services\CityService;
use App\Lib\Auth\UserProfileHelper;

class ActivityController extends Controller
{
    private $userProfileHelper = null;
    private $userGroupService = null;
    private $activityService = null;
    private $cityService = null;

    public function __construct(UserProfileHelper $userProfileHelper,
                                UserGroupService $userGroupService,
                                ActivityService $activityService,
                                CityService $cityService)
    {
        $this->userGroupService  = $userGroupService;
        $this->userProfileHelper = $userProfileHelper;
        $this->activityService   = $activityService;
        $this->cityService       = $cityService;
    }

    public function index(Request $request)
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];
            $currentUserGroup   = $this->userGroupService->getCurrentUserGroup($currentUserGroupId);

            if ($currentUserGroup->isExternalEnterprise()) {
                //同时还要传入当前团队参与的所有的城市
                return view('operations.activity.activity', [
                    'isExternalGroup' => true,
                    'properCities'    => $this->activityService->getProperlyCities($currentUserGroupId)
                ]);
            } else if ($currentUserGroup->isInternalOrganization()) {
                return view('operations.activity.activity', [
                    'isExternalGroup' => false,
                    'properCities'    => $this->activityService->getProperlyCities($currentUserGroupId)
                ]);
            }
        } else {
            return view('backstage.system.user.no_org');
        }
    }

    public function getAllCity(Request $request)
    {
        $cityInfo = $this->cityService->getAllCities();
        return response()->json([
            'cityInfo' => $cityInfo,
            'Success'  => true,
            'Message'  => '',
        ]);
    }

    public function queryActivity(Request $request)
    {
        //return $this->activityService->getActivities($request->all());
    }

    public function create()
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];
            $currentUserGroup   = $this->userGroupService->getCurrentUserGroup($currentUserGroupId);

            if (!empty($currentUserGroup->city_id)) {
                return view('operations.activity.create_act', [
                    'city'            => $currentUserGroup->city,
                    'isExternalGroup' => $currentUserGroup->isExternalEnterprise()
                ]);
            } else {
                return redirect('/backstage/current-org')->withErrors([
                    'error_text' => '当前组织未设置默认地址，因此无法创建活动',
                ]);;
            }
        } else {
            return redirect('/backstage/current-org')->withErrors([
                'error_text' => '未设置当前用户默认地址，因此无法创建活动',
            ]);;
        }
    }

    public function createSave(Request $request)
    {
        $input = $request->all();

        $this->validateWhenActivityNew($input);

        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];
            $cityIds            = explode(',', $input['cityIds']);

            $this->activityService->createActivity($input, $cityIds, [$currentUserGroupId]);
        }

        return response()->json([
            'Success' => true,
            'Message' => '新增活动成功',
        ]);
    }

    public function getActiveActivities(Request $request)
    {
        return $this->activityService
            ->getActivities($request->all(), [
                Activity::$AUDIT_STATUS_PERMITTED
            ]);
    }

    public function indexInActive(Request $request)
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];
            $currentUserGroup   = $this->userGroupService->getCurrentUserGroup($currentUserGroupId);

            if ($currentUserGroup->isExternalEnterprise()) {
                //同时还要传入当前团队参与的所有的城市
                return view('operations.activity.inact_activity', [
                    'isExternalGroup' => true,
                    'properCities'    => $this->activityService->getProperlyCities($currentUserGroupId)
                ]);
            } else if ($currentUserGroup->isInternalOrganization()) {
                return view('operations.activity.inact_activity', [
                    'isExternalGroup' => false,
                    'properCities'    => $this->activityService->getProperlyCities($currentUserGroupId)
                ]);
            }
        } else {
            return view('backstage.system.user.no_org');
        }
    }

    public function getInActiveActivities(Request $request)
    {
        $input = $request->all();

        $auditStatus = [
            Activity::$AUDIT_STATUS_DRAFT,
            Activity::$AUDIT_STATUS_DENIED,
        ];
        //默认只显示待审核以及审批未通过的活动，可以再次提交审批
        if (!empty($input['auditStatus'])) {
            $auditStatus = [$input['auditStatus']];
        }

        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];

            $currentUserGroup = $this->userGroupService->getCurrentUserGroup($currentUserGroupId);

            //外部单位，只可以显示自己单位的活动，需要过滤
            if ($currentUserGroup->isExternalEnterprise()) {
                if (array_key_exists('volunteerGroupInfo', $input)) {
                    unset($input['volunteerGroupInfo']);
                }
                $input['groupId'] = $currentUserGroupId;
            }
        }

        return $this->activityService
            ->getActivities($input, $auditStatus);
    }

    public function toAuditActivity(Request $request)
    {
        $input = $request->all();

        $this->canAuditActivity($input);

        $this->activityService->toAuditActivity($input['activity_id']);

        return response()->json([
            'Success' => true,
            'Message' => '已成功提交审核，请耐心等待',
        ]);
    }

    public function toShowAuditActivity($activityId)
    {
        return view('operations.activity.toaudit_activity', [
            'activity' => Activity::findOrFail($activityId)
        ]);
    }

    public function toDoAuditActivity(Request $request)
    {
        $input = $request->all();

        $this->canDoAuditActivity($input);

        $this->activityService->toDoAuditActivity($input['activity_id']);

        return response()->json([
            'Success' => true,
            'Message' => '审批通过',
        ]);
    }

    public function indexAudit(Request $request)
    {
        return view('operations.activity.audit_activity', [
            'properCities' => $this->cityService->getAllCities()
        ]);
    }

    public function getAuditActivities(Request $request)
    {
        $input = $request->all();

        return $this->activityService
            ->getActivities($input, [
                Activity::$AUDIT_STATUS_TOAUDIT
            ]);
    }

    private function canAuditActivity(Array $input)
    {
        return Validator::make($input, [
            'activity_id' => [
                'required',
                'numeric'
            ]
        ], [
            'activity_id.required' => '必须传入活动ID',
            'activity_id.numeric'  => '活动ID格式不正确，必须为数字',
        ])->after(function ($validator) use ($input) {
            $activity = Activity::findOrFail($input['activity_id']);

            if (!$this->isActivityBelongToCurrentOrg($input['activity_id'])) {
                $validator->errors()->add('audit_status.illegal', '该活动不属于当前组织，不可提交审核');
            }

            if (!in_array($activity->audit_status, [Activity::$AUDIT_STATUS_DRAFT, Activity::$AUDIT_STATUS_DENIED])) {
                $validator->errors()->add('audit_status.illegal', '该活动状态不可提交审核');
            }
        })->validate();
    }

    private function canDoAuditActivity(Array $input)
    {
        return Validator::make($input, [
            'activity_id' => [
                'required',
                'numeric'
            ]
        ], [
            'activity_id.required' => '必须传入活动ID',
            'activity_id.numeric'  => '活动ID格式不正确，必须为数字',
        ])->after(function ($validator) use ($input) {
            $activity = Activity::findOrFail($input['activity_id']);

            if (!in_array($activity->audit_status, [Activity::$AUDIT_STATUS_TOAUDIT])) {
                $validator->errors()->add('audit_status.illegal', '该活动状态不可审批');
            }
        })->validate();
    }

    private function isActivityBelongToCurrentOrg($activityId)
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];

            return $this->activityService->isActivityBelongToCurrentOrg($activityId, $currentUserGroupId);
        }

        return false;
    }

    private function validateWhenActivityNew(Array $input)
    {
        return Validator::make($input, [
            'subject'           => 'required|max:100',
            'picture'           => 'required|max:200',
            'enter_time_start'  => 'required|date_format:Y-m-d H:i|after_or_equal:now',
            'enter_time_end'    => 'required|date_format:Y-m-d H:i|after:enter_time_start',
            'active_time_start' => 'required|date_format:Y-m-d H:i|after_or_equal:enter_time_end',
            'active_time_end'   => 'required|date_format:Y-m-d H:i|after:active_time_start',
            'volunteer_num'     => 'required|numeric',
            'min_volunteer_num' => 'required|numeric|min:1',
            'time_length'       => 'required|numeric',
            'activity_type'     => [
                'required',
                'numeric',
                Rule::in(collect(Activity::$ACTIVITY_TYPE_MAP)->pluck('key')->toArray())
            ],
            'join_method'       => [
                'required',
                'numeric',
                Rule::in(collect(Activity::$USER_JOIN_PERMIT_TYPE_MAP)->pluck('key')->toArray())
            ],
            'description'       => 'required|max:4000',
            'cityIds'           => 'required'
        ], $this->getValidateMessagesWhenActivityNew())->after(function ($validator) use ($input) {
            if (!empty($input['volunteer_num']) && !empty($input['min_volunteer_num'])) {
                if ($input['min_volunteer_num'] > $input['volunteer_num']) {
                    $validator->errors()->add('volunteer_num.mini', '总需求人数不可以小于最小需求人数');
                }
            }
            $cityIds = $input['cityIds'];
            if (!empty($cityIds)) {
                $allValidCityIds = $this->cityService->getAllCities()->pluck('id')->toArray();

                $arrCityIds = explode(',', $cityIds);

                if (count($arrCityIds) != count(array_unique($arrCityIds))) {
                    $validator->errors()->add('cityIds.unique', '存在重复的城市ID');
                } else {
                    $isCityIllegal = true;

                    foreach ($arrCityIds as $curCityId) {
                        if (!empty($curCityId)) {
                            $isCityIllegal = $isCityIllegal && in_array($curCityId, $allValidCityIds);
                        }
                    }

                    if (!$isCityIllegal) {
                        $validator->errors()->add('cityIds.illegal', '传入的城市ID不合法');
                    }
                }
            }
        })->validate();
    }

    private function getValidateMessagesWhenActivityNew()
    {
        return [
            'subject.required'                 => '活动名称必须存在',
            'subject.max'                      => '活动名称长度不可超过:max',
            'picture.required'                 => '还没有上传活动图片',
            'picture.max'                      => '活动图片路径长度不可以超过:max',
            'enter_time_start.required'        => '报名起始时间必须填写',
            'enter_time_start.date_format'     => '报名起始时间格式不正确，只能为yyyy-MM-dd HH:mm格式',
            'enter_time_start.after_or_equal'  => '报名起始时间不得早于当前时间',
            'enter_time_end.required'          => '报名结束时间必须填写',
            'enter_time_end.date_format'       => '报名结束时间格式不正确，只能为yyyy-MM-dd HH:mm格式',
            'enter_time_end.after'             => '报名结束时间必须大于报名起始时间',
            'active_time_start.required'       => '活动起始时间必须填写',
            'active_time_start.date_format'    => '活动起始时间格式不正确，只能为yyyy-MM-dd HH:mm格式',
            'active_time_start.after_or_equal' => '活动起始时间不得早于报名结束时间',
            'active_time_end.required'         => '活动结束时间必须填写',
            'active_time_end.date_format'      => '活动结束时间格式不正确，只能为yyyy-MM-dd HH:mm格式',
            'active_time_end.after'            => '活动结束时间必须大于活动起始时间',
            'volunteer_num.required'           => '必须输入需求人数',
            'volunteer_num.numeric'            => '需求人数格式必须是数字',
            'min_volunteer_num.required'       => '必须输入最低需求人数',
            'min_volunteer_num.numeric'        => '最低需求人数格式必须是数字',
            'min_volunteer_num.min'            => '最低需求人数不可低于:min',
            'time_length.required'             => '必须输入活动可获公益时长',
            'time_length.numeric'              => '活动可获公益时长必须是数字',
            'activity_type.required'           => '必须输入活动类型',
            'activity_type.numeric'            => '活动类型必须是数字',
            'activity_type.in'                 => '活动类型的传入值不正确',
            'join_method.required'             => '必须传入志愿者参与方式',
            'join_method.numeric'              => '志愿者参与方式必须是数字',
            'join_method.in'                   => '志愿者参与方式的传入值不正确',
            'description.required'             => '必须输入活动详情',
            'description.max'                  => '活动详情内容过长',
            'cityIds.required'                 => '必须输入至少一个活动城市',
        ];
    }

    /*
     * name:后台活动审核
     * author:hy
     * param:$request
     */
    public function applyActivityAudit()
    {
        return view('operations.activity.apply_activity_audit', [
            'properCities' => $this->cityService->getAllCities()
        ]);
    }

    /*
     * name:后台活动审核数据
     * author:hy
     * param:$request
     */
    public function getUserApplyActivityData(Request $request)
    {
        $input = $request->all();
        return $this->activityService
            ->getUserApplyActivities($input);
    }

    /*
     * name:后台活动审核页面
     * author:hy
     * param:$request
     */
    public function UserApplyIndex(Request $request)
    {
        $input = $request->all();
        return view('operations.activity.user_apply_toaudit_activity', [
            'applyInfo' => $this->activityService->getUserApplyActivitiesDetail($input)
        ]);
    }

    /*
     * name:拒绝申请
     * author:hy
     * param:$request
     */
    public function denyUserApply(Request $request)
    {
        $input = $request->all();
        $this->activityService->denyUserApply($input);
        return ResponseUtil::jsonResponse(true, 0, '审核成功', '');
    }

    /*
     * name:同意申请
     * author:hy
     * param:$request
     */
    public function passUserApply(Request $request)
    {
        $input = $request->all();
        $this->activityService->passUserApply($input);
        return ResponseUtil::jsonResponse(true, 0, '审核成功', '');
    }
}
